package com.tedu.day08_springmvc.controller;

import com.tedu.day08_springmvc.mapper.IUserMapper;
import com.tedu.day08_springmvc.pojo.dto.UserDTO;
import com.tedu.day08_springmvc.pojo.entity.User;
import com.tedu.day08_springmvc.pojo.vo.UsersVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

//@Controller
@RestController//使用该注解后，所有方法不必再添加@ResponseBody
public class UserController {
    /*@Autowired(required=true)：
    当使用@Autowired注解的时候，其实默认就是@Autowired(required=true)，表示注入的时候，该bean必须存在，否则就会注入失败。
    @Autowired(required=false)：
    表示忽略当前要注入的bean，如果有直接注入，没有跳过，不会报错。*/
    @Autowired
    private IUserMapper iUserMapper;
    //@RequestMapping(value = "/user/register",method = RequestMethod.POST)
    @PostMapping("/user/register")
    //@ResponseBody
    public String register(UserDTO userDTO){
        System.out.println("进入注册逻辑");
        System.out.println(userDTO);
        User user = new User();
        BeanUtils.copyProperties(userDTO,user);//将userDTO的属性值拷贝到user对应的属性中
        System.out.println(user);
        user.setCreated(new Date());
        int rows = iUserMapper.insertUser(user);


        return rows>0?"注册成功":"注册失败";

    }

    //@RequestMapping(value = "/user/delete",method = RequestMethod.DELETE)
    //@DeleteMapping("/user/delete")
    @DeleteMapping("/user/delete/{id}")
    //@ResponseBody
    public String delete(@PathVariable Integer id){
        //@PathVariable:从地址中获取参数
        int rows = iUserMapper.deleteUserById(id);
        return rows>0?"删除成功":"删除失败";
    }

    //@RequestMapping(value = "user/update",method = RequestMethod.PUT)
    @PutMapping("/user/update")
    //@ResponseBody
    public String update(UserDTO userDTO){
        User user = new User();
        BeanUtils.copyProperties(userDTO,user);
        int rows = iUserMapper.updateUserByUsername(user);

        return rows>0?"修改成功":"修改失败";
    }

    //@RequestMapping(value = "/user/findAll",method = RequestMethod.GET)
    @GetMapping("/user/findAll")
    //@ResponseBody
    public List<UsersVO> findUsers(){
        System.out.println("查询所有用户");
        List<UsersVO> vos = iUserMapper.selectAllUser();
        return vos;
    }

    @GetMapping("/user/find/{id}")
    public UsersVO findById(@PathVariable int id){

        return iUserMapper.selectById(id);
    }
}
